package com.googlecode.gwtbb.client.only.widget.display.forum;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.SimplePanel;
import com.googlecode.gwtbb.client.only.glue.PathUtils;
import com.googlecode.gwtbb.client.shared.entity.forum.Forum;
import com.googlecode.gwtbb.client.shared.entity.forum.Post;
import com.googlecode.gwtbb.client.shared.remote.forum.ForumPost;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 16, 2008
 */
public class ThreadLink extends Composite {
	private SimplePanel mainPanel;
	private ForumPost forumPost;

	public static String buildTarget(Post thread, Forum forum) {
		if (!thread.isThread())
			return null;
		String subject = thread.getSubject();
		String target = PathUtils.concatToken(thread.getId(), subject);
		target = PathUtils.makeSubToken(PathUtils.concatToken(forum.getId(), forum.getName()), target);
		target = PathUtils.link(target);
		return target;
	}

	public ThreadLink(ForumPost forumPost) {
		mainPanel = new SimplePanel();
		initWidget(mainPanel);
		setForumPost(forumPost);
	}

	public ForumPost getForumPost() {
		return forumPost;
	}

	public void clear() {
		mainPanel.setWidget(null);
	}

	public void setForumPost(ForumPost forumPost) {
		this.forumPost = forumPost;
		mainPanel.setWidget(buildLink(forumPost));
	}

	private Hyperlink buildLink(ForumPost forumPost) {
		Hyperlink link = new Hyperlink();
		if (forumPost != null) {
			Post thread = forumPost.getPost();
			if (thread != null && thread.isThread()) {
				Forum forum = forumPost.getForum();
				if (forum != null) {
					link.setText(thread.getSubject());
					link.setTargetHistoryToken(buildTarget(thread, forum));
				}
			}
		}
		return link;
	}
}